﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;



namespace Quaack
{
    public partial class Registreer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // validatie properties
            CreateUserWizard1.CreateUserButtonText = (string) GetLocalResourceObject("btnCreate.Text");
            CreateUserWizard1.CreateUserButtonStyle.CssClass = "btn btn-block";
            CreateUserWizard1.CancelButtonText = (string) GetLocalResourceObject("btnCancel.Text");
            CreateUserWizard1.CancelButtonStyle.CssClass = "btn btn-block";
            CreateUserWizard1.CompleteSuccessText = (string) GetLocalResourceObject("regCompleet.Text");
            CreateUserWizard1.CompleteSuccessTextStyle.CssClass = "text-success";
            CreateUserWizard1.ContinueButtonText = (string) GetLocalResourceObject("btnContinue.Text");
            CreateUserWizard1.ContinueButtonStyle.CssClass = "btn btn-block";
        }

        protected void btnAnnuleer_Click(object sender, EventArgs e)
        {
            Response.Redirect("ZoekGebruiker.aspx");
        }

        protected void CreateUserWizard1_CreatingUser(object sender, LoginCancelEventArgs e)
        {
            if (Page.IsValid)
            {
                // connectiestring uit de web.config
                string connectionString = ConfigurationManager.ConnectionStrings["QuaackSqlConnection"].ConnectionString;

                // waardes die gecheckt moeten worden in de Quaack tabellen
                String gebruikersNaam =
                    ((TextBox) CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName")).Text.
                        Trim();
                String email =
                    ((TextBox) CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email")).Text.Trim
                        ();
                String mobielNR =
                    ((TextBox) CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtMobielNR")).
                        Text.Trim();

                using (var connection = new SqlConnection(connectionString))
                {
                    // queries voor het checken op bestaande gegevens in database, SELECT COUNT(*) telt aan hits op zoekresultaat
                    var queryCheckEmail = "SELECT COUNT(*) as Email FROM [Quaack].[dbo].[profile] WHERE email = '" +
                                          email + "'";
                    var queryCheckGebruikersNaam =
                        "SELECT COUNT(*) as GebruikersNaam FROM [Quaack].[dbo].[profile] WHERE username = '" +
                        gebruikersNaam + "'";
                    var queryCheckMobielNR =
                        "SELECT COUNT(*) as GebruikersNaam FROM [Quaack].[dbo].[profile] WHERE mobilenumber = '" +
                        mobielNR + "'";

                    var cmdEmail = new SqlCommand(queryCheckEmail, connection);
                    var cmdGebruikersNaam = new SqlCommand(queryCheckGebruikersNaam, connection);
                    var cmdMobielNR = new SqlCommand(queryCheckMobielNR, connection);

                    connection.Open();

                    var emailCount = (Int32) cmdEmail.ExecuteScalar();
                    var gebruikersNaamCount = (Int32) cmdGebruikersNaam.ExecuteScalar();
                    var mobielNRcount = (Int32) cmdMobielNR.ExecuteScalar();

                    // Als er geen mobielnummer is ingevuld mobielNR COUNT weer op 0 zetten
                    if (String.IsNullOrEmpty(mobielNR))
                    {
                        mobielNRcount = 0;
                    }

                    if (gebruikersNaamCount > 0)
                    {
                        lblError.Text = (string) GetLocalResourceObject("ErrorGebruikersNaamDubbel.Text");
                        e.Cancel = true;
                        return;
                    }
                    if (emailCount > 0)
                    {
                        lblError.Text = (string) GetLocalResourceObject("ErrorEmailDubbel.Text");
                        e.Cancel = true;
                        return;
                    }
                    if (mobielNRcount > 0)
                    {
                        lblError.Text = (string) GetLocalResourceObject("ErrorMobielNRdubbel.Text");
                        e.Cancel = true;
                    }
                }
            }
            else
            {
                return;
            }
        }

        protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
        {
            // Connectiestring uit de web.config
            string connectionString = ConfigurationManager.ConnectionStrings["QuaackSqlConnection"].ConnectionString;

            // profiel gegevens welke naar de Quaack tabellen worden geschreven
            String gebruikersNaam = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName")).Text.Trim();
            String wachtWoord = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("passWord")).Text.Trim();
            String email = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email")).Text.Trim();
            String profielTekst = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtProfielTekst")).Text.Trim();
            String mobielNR = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtMobielNR")).Text.Trim();
            String avatar = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtAvatar")).Text.Trim();

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                // UserId nieuwe gebruiker
                var newUser = Membership.GetUser(CreateUserWizard1.UserName);

                var newUserId = (Guid)newUser.ProviderUserKey;

                // alle blokkades in de Quaack database op 0 zetten = false
                const int geldigeGebruiker = 0;

                // query voor schrijven naar de Quaack tabellen
                var insertSql =
                    "INSERT INTO dbo.profile (username, password, profile, email, avatarlocation, mobilenumber, verificationpending, tempblocked, permblocked, removed) VALUES "
                    +
                    " (@username,@password,@profile,@email,@avatarlocation,@mobilenumber,@verificationpending,@tempblocked,@permblocked,@removed)";

                using (var myConnection = new SqlConnection(connectionString))
                {
                    myConnection.Open();

                    var myCommand = new SqlCommand(insertSql, myConnection);

                    // variabelen naar database
                    myCommand.Parameters.AddWithValue("@UserId", newUserId);
                    myCommand.Parameters.AddWithValue("@username", gebruikersNaam);
                    myCommand.Parameters.AddWithValue("@password", wachtWoord);
                    myCommand.Parameters.AddWithValue("@profile", profielTekst);
                    myCommand.Parameters.AddWithValue("@email", email);
                    myCommand.Parameters.AddWithValue("@avatarlocation", avatar);
                    myCommand.Parameters.AddWithValue("@mobilenumber", mobielNR);
                    myCommand.Parameters.AddWithValue("@verificationpending", geldigeGebruiker);
                    myCommand.Parameters.AddWithValue("@tempblocked", geldigeGebruiker);
                    myCommand.Parameters.AddWithValue("@permblocked", geldigeGebruiker);
                    myCommand.Parameters.AddWithValue("@removed", geldigeGebruiker);

                    myCommand.ExecuteNonQuery();

                    myConnection.Close();
                }
            }
        }

        protected void CreateUserWizard1_SendingMail(object sender, MailMessageEventArgs e)
        {
            // registratie email versturen
            var newUserAccount = Membership.GetUser(CreateUserWizard1.UserName);
            var newUserAccountId = (Guid)newUserAccount.ProviderUserKey;

            // url maken
            string domainName = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
            string confirmationPage = "Anoniem/BevestigAccount.aspx?ID=" + newUserAccountId.ToString();
            string url = domainName + confirmationPage;
            string gebruikersNaam = HttpContext.Current.User.Identity.Name;


            e.Message.Body = e.Message.Body.Replace("<%VerificationUrl%>", url);
            e.Message.Body = e.Message.Body.Replace("<%UserName%>", gebruikersNaam);

            // mail client
            var smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.UseDefaultCredentials = false;

            smtp.Credentials = new NetworkCredential("quaackwebapp@gmail.com", "quaack2013");

            smtp.EnableSsl = true;
            smtp.Send(e.Message);

            e.Cancel = true;
        }
    }
}




